<?php
use Phinx\Migration\AbstractMigration;

class ConvertOptionsToKv extends AbstractMigration
{
    public function up()
    {
        // Convert options for single/multi/judge into {A: text, B: text} JSON if they are stored as indexed arrays
    $rows = $this->fetchAll('SELECT id, type, options FROM ba_exam_question WHERE type IN ("single","multi","judge")');
        $count = 0;
        foreach ($rows as $r) {
            $id = $r['id'];
            $opts = $r['options'];
            if ($opts === null || $opts === '') continue;
            $parsed = json_decode($opts, true);
            if ($parsed === null) {
                // not valid json: skip
                continue;
            }
            // if associative (already kv) skip
            if (is_array($parsed) && array_values($parsed) !== $parsed) continue;
            // if numeric-indexed array, convert
            if (is_array($parsed)) {
                $obj = [];
                foreach ($parsed as $i => $text) {
                    $k = chr(65 + intval($i));
                    $obj[$k] = $text;
                }
                $this->execute('UPDATE ba_exam_question SET options = ? WHERE id = ?', [json_encode($obj, JSON_UNESCAPED_UNICODE), $id]);
                $count++;
            }
        }
        echo "Converted {$count} rows to key-value options\n";
    }

    public function down()
    {
        // try to revert kv to array (best-effort)
    $rows = $this->fetchAll('SELECT id, options FROM ba_exam_question');
        $count = 0;
        foreach ($rows as $r) {
            $id = $r['id'];
            $opts = $r['options'];
            if ($opts === null || $opts === '') continue;
            $parsed = json_decode($opts, true);
            if ($parsed === null) continue;
            if (is_array($parsed) && array_values($parsed) === $parsed) continue; // already array
            // associative -> values
            if (is_array($parsed)) {
                $vals = array_values($parsed);
                $this->execute('UPDATE ba_exam_question SET options = ? WHERE id = ?', [json_encode($vals, JSON_UNESCAPED_UNICODE), $id]);
                $count++;
            }
        }
        echo "Reverted {$count} rows to array options\n";
    }
}
